package gameStates.network;

import java.util.HashMap;
import java.util.Set;
import java.util.logging.Logger;

public class IDContainer<T extends IDObject> {
	
	private static final Logger logger = Logger.getLogger("gameStates.network.IDContainer");
	
	private HashMap<Integer, T> data;
	private int lastID;
	private boolean overflown;
	
	public IDContainer() {
		data = new HashMap<Integer, T>();
		lastID = 1;
		overflown = false;
	}
	
	public int register(T obj) {
		int newID = lastID;
		register(obj, newID);
		return newID;
	}
	
	public void register(T obj, int id) {
		if(id <= 0) register(obj);
		else {
			T other = get(id);
			if(other != null) {
				if(other != obj) 
					logger.severe("id " + id + " already mapped to " + get(id) + ", so " + obj + " cannot be mapped to it.");
				assert(other == obj);
			} else {
				Integer index = Integer.valueOf(id);
				logger.info("putting " + obj + " to " + index.intValue());
				data.put(index, obj);
				obj.setID(id);
				if(lastID <= id) lastID = id + 1;
				if(lastID < 0) {
					logger.info("overflow with " + obj.getClass().getSimpleName());
					lastID = 100;
					overflown =  true;
				}
				if(overflown) unregister(lastID);
			}
		}
	}
	
	public boolean contains(int id) {
		return data.containsKey(Integer.valueOf(id));
	}
	
	public T get(int id) {
		return data.get(Integer.valueOf(id));
	}
	
	public void unregister(int id) {
		data.remove(Integer.valueOf(id));
	}
	
	public Set<Integer> keySet() { return data.keySet(); }
}